package com.atqh.srrt.chicken.controller.TestController;

import com.atqh.srrt.chicken.Aop.LogAnnotation;
import com.atqh.srrt.chicken.Multithreading.UserThreadLocal;
import com.atqh.srrt.chicken.domain.SysUser;
import com.atqh.srrt.chicken.domain.UserRegular;
import com.atqh.srrt.chicken.mapper.UserRegularMapper;
import com.atqh.srrt.chicken.utils.Result;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @作者：大叔azhe
 * @api：详细描述
 * @创建时间：12:55 2024/4/8
 */
@RestController
@RequestMapping("/test1")
public class test1Controller {

    @Autowired
    private UserRegularMapper userRegularMapper;

    @Value("${firstFilePath}")
    private String firstFilePath;

    @RequestMapping("/getCurrent")
    @LogAnnotation(module = "问卷模块",operator = "用户首次登录填写问卷")
    public Result login(){

        SysUser sysUser = UserThreadLocal.get();
        if (sysUser==null){
            return Result.Fail(400,"未登录");
        }

        LambdaQueryWrapper<UserRegular> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRegular::getUserId,sysUser.getId()).last("limit 1");

        return Result.success(userRegularMapper.selectOne(queryWrapper));

    }
    @RequestMapping("/down")
    public void downFile(HttpServletResponse response) {
        try {
            response.setCharacterEncoding("UTF-8");
            String fileName = "firstStageTemplate.doc";
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            String filePath = firstFilePath + File.separator + fileName;

            File file = new File(filePath);
            if (!file.exists()) {
                throw new FileNotFoundException("File not found: " + filePath);
            }

            // 设置下载文件的ContentType
            String contentType = "application/octet-stream"; // 默认为二进制流
            if (fileName.endsWith(".doc")) {
                contentType = "application/msword";
            } else if (fileName.endsWith(".pdf")) {
                contentType = "application/pdf";
            } // 添加其他可能的文件类型

            response.setContentType(contentType);
            response.setContentLength((int) file.length());
            response.setHeader("Content-disposition", "attachment; filename=" + fileName);

            try (FileInputStream inputStream = new FileInputStream(file);
                 OutputStream os = response.getOutputStream()) {
                byte[] buffer = new byte[1024];
                int length;
                while ((length = inputStream.read(buffer)) != -1) {
                    os.write(buffer, 0, length);
                }
                os.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (UnsupportedEncodingException | FileNotFoundException e) {
            e.printStackTrace();
        }
    }


    @GetMapping("/downloadDoc")
    public ResponseEntity<byte[]> downloadDocFile() throws IOException {
//        String fileName = "firstStageTemplate.doc";
//        String filePath = firstFilePath + File.separator + fileName;
        ClassPathResource resource = new ClassPathResource("firstStageTemplate.doc");
        InputStream inputStream = resource.getInputStream();


        // 使用ByteArrayOutputStream将InputStream中的所有字节读取到一个字节数组中
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, length);
        }
        byte[] fileBytes = outputStream.toByteArray();

        // 关闭InputStream和ByteArrayOutputStream
        inputStream.close();
        outputStream.close();

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", "firstStageTemplate.doc");
        headers.setContentLength(fileBytes.length);


        // 返回ResponseEntity
        return ResponseEntity.ok()
                .headers(headers)
                .body(fileBytes);
    }


    @PostMapping("/upload")
    @ResponseBody
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return new ResponseEntity<>("请选择要上传的文件", HttpStatus.BAD_REQUEST);
        }

        try {
            // 获取上传文件的原始名称
            String originalFilename = StringUtils.cleanPath(file.getOriginalFilename());
            // 检查文件类型，仅允许上传 .doc, .docx 或 .pdf 文件
            if (!originalFilename.endsWith(".doc") && !originalFilename.endsWith(".docx") && !originalFilename.endsWith(".pdf")) {
                return new ResponseEntity<>("仅允许上传 .doc, .docx 或 .pdf 文件", HttpStatus.BAD_REQUEST);
            }

            // 创建保存文件的目录
            File uploadDir = new File(firstFilePath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 保存文件到本地
            Path filePath = Paths.get(firstFilePath + originalFilename);
            Files.write(filePath, file.getBytes());

            return new ResponseEntity<>("文件上传成功", HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>("文件上传失败", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

}
